package com.fatmeraid.service.impl;

import com.fatmeraid.common.constant.RedisConstant;
import com.fatmeraid.common.exception.FarmException;
import com.fatmeraid.common.result.ResultCodeEnum;
import com.fatmeraid.common.utils.JwtUtil;
import com.fatmeraid.dao.UserDao;
import com.fatmeraid.domain.User;
import com.fatmeraid.vo.Captcha;
import com.fatmeraid.vo.LoginVo;
import com.fatmeraid.service.LoginService;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	private UserDao userDao;

	@Override
	public Captcha getCaptcha() {
		// 创建验证码 宽 130 高 48 验证码位数 5
		SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
		// 获取验证码内容
		String code = specCaptcha.text().toLowerCase();
		// 生成key
		String key =  RedisConstant.LOGIN_PREFIX +" "+UUID.randomUUID().toString();
		// 存入redis
		stringRedisTemplate.opsForValue().set(key,code,RedisConstant.LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
		return new Captcha(specCaptcha.toBase64(),key);
	}


	@Override
	public String login(LoginVo loginVo) {

		// 验证码不能为空
		if (loginVo.getCaptchaCode()== null  ){
			throw new FarmException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
		}
		// 获取redis中的验证码
		String code = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
		System.out.println(code+"---------");
		// 判断验证码是否过期
		if (code == null){
			throw new FarmException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
		}
		System.out.println(loginVo.getCaptchaCode().toLowerCase());
		// 判断验证码是否相同
		if(!loginVo.getCaptchaCode().toLowerCase().equals(code)){
			throw new FarmException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
		}
		// 查询用户是否存在
		User user = userDao.selectOneByUsername(loginVo.getUsername());
		// 判断用户是否存在
		if (user == null){
			throw new FarmException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
		}
		// 判断用户是否被禁用
		if (user.getStatus() == 0){
			throw new FarmException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
		}

		//对输入密码进行 MD5 加密（与注册时规则一致）
		String inputEncrypted = DigestUtils.md5DigestAsHex(
				loginVo.getPassword().getBytes(StandardCharsets.UTF_8)
		);
		// 验证密码是否正确
		if(!user.getPassword().equals(inputEncrypted)){
			throw new FarmException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
		}
		// 生成token
		String token = JwtUtil.createToken(user.getUserId(),user.getUsername());

		return token;
	}

	@Override
	public User getLoginUserInfoById(Long userId) {
		System.out.println("userId:"+userId);
		User user = userDao.selectById(userId);
		return user;
	}


}
